import asyncio
import re

import httpx
import requests
from playwright.async_api import async_playwright, Playwright, Route

cc = re.match(r"^https://challenges\.cloudflare\.com/turnstile/v0/api\.js\?onload=onloadTurnstileCallback__cf-turnstile&render=explicit$", "https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onloadTurnstileCallback__cf-turnstile&render=explicit")
print(cc)
exit()

async def getWsVersion():
    req = requests.get(url="http://localhost:9222/json/version")

    return req.json()


async def run(playwright: Playwright):
    # 使用现有浏览器实例的 WebSocket 地址连接
    browser = await playwright.chromium.connect_over_cdp("http://localhost:9222")
    page = await browser.new_page()

    # 拦截特定 JS 文件
    async def handle_js(route, request):
        url = request.url
        print(f"🔍 拦截 JS: {url}")
        if "https://lf-douyin-pc-web.douyinstatic.com/obj/douyin-pc-web/ies/douyin_web/async/46514.6a47101e.js" == url:

            # 请求原始 JS 内容
            async with httpx.AsyncClient() as client:
                resp = await client.get(url)
                original_js = resp.text
                # print(original_js)
            # 修改 JS 内容（这里替换函数内容）
            modified_js = original_js.replace(
                "XMLHttpRequest.prototype.send=function(){", "XMLHttpRequest.prototype.send=function(){console.log(this);"  # 举例：修改日志级别
            )

            # 响应修改后的 JS
            await route.fulfill(
                status=200,
                content_type="application/javascript",
                body=modified_js
            )
        else:
            await route.continue_()

    # 开启路由拦截
    await page.route("**/*.js", handle_js)

    await page.goto("https://www.douyin.com/?recommend=1")
    print(await page.title())
    await page.wait_for_timeout(100000)  # 等待查看效果


async def main():
    async with async_playwright() as playwright:
        await run(playwright)


asyncio.run(main())
